package ezy.widget.pullrefresh;

import android.content.Context;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

class PullLayout extends FrameLayout {

    public final boolean isHeader;
    public IPullIndicator indicator;

    private int contentHeight = 0;
    private LinearLayout _wrapper;
    private View _content;
    private LayoutParams _lp = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0);

    public PullLayout(Context context, boolean isHeader) {
        super(context);
        this.isHeader = isHeader;

        _wrapper = new LinearLayout(context);
        _wrapper.setGravity(isHeader ? Gravity.BOTTOM : Gravity.TOP);
        addView(_wrapper, _lp);
    }

    public boolean isReady() {
        return getLayoutHeight() > contentHeight + indicator.getPullHeight();
    }

//    public boolean canPull(float delta) {
////        return isEnabled() && (delta > 0 || getPullValue() <= 0);
//        return isEnabled() && (delta > 0);
//    }

    public int getLayoutHeight() {
        return _lp.height;
    }
    public void setLayoutHeight(int value) {
        _lp.height = Math.max(0, value);
        _wrapper.setLayoutParams(_lp);
    }

    public int getPullValue() {
        return (getLayoutHeight() - (indicator.isHide() ? 0 : contentHeight));
    }
    public void setPullValue(int value) {
        int height = value + (indicator.isHide() ? 0 : contentHeight);
        setLayoutHeight(height);
        if (height != 0 && contentHeight != 0) {
            indicator.onPulling(height / contentHeight);
        }
    }

    public void onState(PullRefreshList.State state) {
        indicator.onState(state);
    }


    public void init() {
        if (indicator == null) {
            throw new NullPointerException("pull indicator can not be null.");
        }
        _content = indicator.onCreateView(_wrapper);
        if (_content == null) {
            throw new NullPointerException("pull indicator view can not be null.");
        }
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) _content.getLayoutParams();
        if (lp == null) {
            lp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        }
        _wrapper.addView(_content, lp);

        getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                contentHeight = _content.getHeight();
                getViewTreeObserver().removeGlobalOnLayoutListener(this);
            }
        });
    }
}